﻿using System.IO;
using System.Text;

namespace LaserMark.Extensions
{
    public static class OPTRead
    {
        public static IDictionary<string, string?> Read(Stream stream)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
            int count = 0;
            int info = 0;
            using (var reader = new StreamReader(stream, Encoding.GetEncoding("GB2312")))
            {
                string sectionPrefix = string.Empty;
                while (reader.Peek() != -1)
                {
                    try
                    {
                        string rawLine = reader.ReadLine()!; // Since Peak didn't return -1, stream hasn't ended.
                        string line = rawLine.Trim();

                        // Ignore blank lines
                        if (string.IsNullOrWhiteSpace(line))
                        {
                            continue;
                        }
                        // Ignore comments
                        if (line[0] is ';' or '#' or '/')
                        {
                            continue;
                        }

                        // [Section:header]
                        if (line[0] == '[' && line[line.Length - 1] == ']')
                        {
                            // remove the brackets
                            sectionPrefix = line.AsSpan(1, line.Length - 2).Trim().ToString();
                            if (sectionPrefix == "OPT_Pattern")
                            {
                                info = 0;
                                count++;
                            }
                            if (sectionPrefix == "Info")
                            {
                                info++;
                            }
                            continue;
                        }

                        string key = "";
                        string value = "";

                        if (sectionPrefix == "Cuttings")
                        {
                            key = sectionPrefix + count;
                            if (data.Keys.Any(s => s == key))
                            {
                                key = sectionPrefix + count.ToString();
                            }
                            value = line + ",";
                            while (sectionPrefix == "Cuttings")
                            {
                                string pos = reader.ReadLine()!;
                                if (string.IsNullOrWhiteSpace(pos))
                                {
                                    break;
                                }
                                value += pos + ",";
                            }
                        }
                        else
                        {
                            // key = value OR "value"
                            int separator = line.IndexOf('=');
                            key = sectionPrefix + count + line.Substring(0, separator).Trim();
                            if (data.Keys.Any(s => s == key))
                            {
                                key = sectionPrefix + count + line.Substring(0, separator).Trim();
                            }
                            if (key == $"Info{count}{line.Substring(0, separator).Trim()}")
                            {
                                key = $"Info{count}{info}{line.Substring(0, separator).Trim()}";
                            }
                            value = line.Substring(separator + 1).Trim();

                            if (key == $"OPT_Pattern{count}X")
                            {
                                key = $"OPT_Pattern{count}XYZW";
                                value = line + ",";
                                while (key == $"OPT_Pattern{count}XYZW")
                                {
                                    var pos = reader.ReadLine()!;
                                    if (string.IsNullOrEmpty(pos))
                                    {
                                        break;
                                    }
                                    value += pos.Trim() + ",";
                                }
                            }

                            // Remove quotes
                            if (value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"')
                            {
                                value = value.Substring(1, value.Length - 2);
                            }
                        }
                        data[key] = value;

                    }
                    catch (Exception ex)
                    {

                    }
                }
                data["Count"] = count.ToString();
            }
            return data;
        }
    }
}
